<template>
  <div class="chat-container">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="logo">
          <i class="el-icon-plant"></i>
          <span>农业知识咨询</span>
        </div>
      </div>
      <div class="sidebar-content">
        <div class="session-filter">
          <!-- <el-input placeholder="搜索专家..." prefix-icon="el-icon-search" size="small" class="search-input"></el-input> -->
        </div>
        <div class="session-list">
          <div v-for="session in sessions" :key="session.expertId" 
               :class="['session-card', session.expertId === currentExpertId ? 'active' : '']" 
               @click="selectSession(session)">
            <div class="session-avatar">
              <el-avatar :src="session.expert && session.expert.avatar ? getImageUrl(session.expert.avatar) : ''" icon="el-icon-user-solid"></el-avatar>
              <div class="online-status" v-if="session.expert && session.expert.online">在线</div>
            </div>
            <div class="session-info">
              <div class="session-name">{{ session && session.expert.name }}</div>
              <div class="session-title">{{ session && session.expert.title || '农业专家' }}</div>
              <div class="session-preview" v-if="getLastMessage(session.expertId)">
                <span class="preview-text">{{ getLastMessage(session.expertId).content }}</span>
                <span class="preview-time">{{ formatTime(getLastMessage(session.expertId).sendTime) }}</span>
              </div>
            </div>
            <div class="session-badge" v-if="unreadMap[session.expertId]">{{ unreadMap[session.expertId] }}</div>
          </div>
          <el-empty v-if="!sessions.length" description="暂无会话" class="empty-sessions"></el-empty>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <div v-if="currentExpertId" class="chat-content">
        <div class="chat-header">
          <div class="header-info">
            <div class="header-avatar">
              <el-avatar :src="currentSession.expert && currentSession.expert.avatar ? getImageUrl(currentSession.expert.avatar) : ''" icon="el-icon-user-solid"></el-avatar>
            </div>
            <div class="header-text">
              <div class="header-name">{{ currentSession.expert && currentSession.expert.name }}</div>
              <div class="header-status">{{ currentSession.expert && currentSession.expert.title }}</div>
            </div>
          </div>
          <div class="header-actions">
            <el-tooltip content="刷新消息" placement="bottom">
              <el-button icon="el-icon-refresh" circle size="small" @click="refreshMessages"></el-button>
            </el-tooltip>
          </div>
        </div>

        <div class="message-container" ref="msgBox">
          <div class="chat-date">
            <span>今天</span>
          </div>
          <div v-for="msg in messages" :key="msg.id" :class="['message-wrapper', msg.fromExpert ? 'expert' : 'user']">
            <div class="message-avatar" v-if="msg.fromExpert">
              <el-avatar :src="getImageUrl(currentSession.expert.avatar)" size="small" icon="el-icon-user-solid"></el-avatar>
            </div>
            <div class="message-body">
              <div class="message-sender" v-if="msg.fromExpert">{{ currentSession.expert.name }}</div>
              <div class="message-bubble">
                {{ msg.content }}
              </div>
              <div class="message-time">{{ formatTime(msg.sendTime) }}</div>
            </div>
            <div class="message-avatar user-avatar" v-if="!msg.fromExpert">
              <el-avatar :src="userInfo.avatar" size="small" icon="el-icon-user-solid"></el-avatar>
            </div>
          </div>
          <div class="typing-indicator" v-if="isTyping">
            <div class="typing-bubble">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>

        <div class="chat-footer">
          <div class="message-input-wrapper">
            <div class="message-tools">
              <el-tooltip content="表情" placement="top">
                <i class="el-icon-star-off tool-icon"></i>
              </el-tooltip>
              <el-tooltip content="图片" placement="top">
                <i class="el-icon-picture-outline tool-icon"></i>
              </el-tooltip>
              <el-tooltip content="文件" placement="top">
                <i class="el-icon-document tool-icon"></i>
              </el-tooltip>
            </div>
            <div class="message-input">
              <el-input 
                v-model="input" 
                type="textarea" 
                :rows="2" 
                placeholder="输入您的问题..." 
                resize="none"
                @keyup.enter.native.ctrl="send">
              </el-input>
            </div>
            <div class="message-send">
              <el-button type="primary" @click="send" :disabled="!input.trim()" icon="el-icon-position" circle></el-button>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-chat">
        <div class="empty-chat-content">
          <i class="el-icon-message"></i>
          <p>选择一个专家开始咨询</p>
          <el-button type="primary" size="medium" @click="goToExpertList">浏览专家列表</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserSessions, getHistory } from '../../api/ChatController';
import { sendChatMessage, connectChatSocket, closeChatSocket } from '../../api/chatSocket';
export default {
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('frontUser') || '{}'),
      sessions: [],
      currentExpertId: null,
      currentSession: {},
      messagesMap: {}, // { expertId: [msg, ...] }
      input: '',
      unreadMap: {}, // { expertId: count }
      isTyping: false,
    };
  },
  methods: {
    async loadSessions() {
      const res = await getUserSessions(this.userInfo.id);
      this.sessions = Array.isArray(res) ? res : (res.data || []);
      if (this.sessions.length) {
        this.selectSession(this.sessions[0]);
      }
    },
    async selectSession(session) {
      this.currentExpertId = session.expertId;
      this.currentSession = session;
      // 拉取历史消息
      const res = await getHistory({ userId: this.userInfo.id, expertId: session.expertId });
      this.$set(this.messagesMap, session.expertId, Array.isArray(res) ? res : (res.data || []));
      this.$set(this.unreadMap, session.expertId, 0);
      this.$nextTick(this.scrollToBottom);
    },
    handleSocketMessage(msg) {
      console.log('用户收到消息', msg, this.userInfo.id);
      if (!msg || msg.userId !== this.userInfo.id && msg.expertId !== this.userInfo.id) return;
      const expertId = msg.expertId;
      if (!this.messagesMap[expertId]) this.$set(this.messagesMap, expertId, []);
      this.messagesMap[expertId].push(msg);
      if (this.currentExpertId === expertId) {
        this.$nextTick(this.scrollToBottom);
      } else {
        this.$set(this.unreadMap, expertId, (this.unreadMap[expertId] || 0) + 1);
      }
    },
    send() {
      if (!this.input.trim()) return;
      const msg = {
        expertId: this.currentExpertId,
        userId: this.userInfo.id,
        content: this.input.trim(),
        fromExpert: false,
        sendTime: new Date().toISOString()
      };
      sendChatMessage(msg);
      this.input = '';
      this.$nextTick(this.scrollToBottom);
    },
    scrollToBottom() {
      const box = this.$refs.msgBox;
      if (box) box.scrollTop = box.scrollHeight;
    },
    getImageUrl(url) {
      if (!url) return '';
      return url.startsWith('/api') ? url : `/api${url}`;
    },
    formatTime(time) {
      if (!time) return '';
      if (typeof time === 'string') {
        // 兼容 ISO 字符串和 yyyy-MM-dd HH:mm:ss
        if (time.includes('T')) {
          return time.replace('T', ' ').substring(11, 16); // 只显示时:分
        }
        return time.substring(11, 16); // 只显示时:分
      }
      if (typeof time === 'number') {
        // 毫秒时间戳
        const date = new Date(time);
        const pad = n => n < 10 ? '0' + n : n;
        return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
      }
      if (time instanceof Date) {
        const pad = n => n < 10 ? '0' + n : n;
        return `${pad(time.getHours())}:${pad(time.getMinutes())}`;
      }
      return String(time);
    },
    getLastMessage(expertId) {
      const messages = this.messagesMap[expertId] || [];
      return messages.length ? messages[messages.length - 1] : null;
    },
    refreshMessages() {
      if (this.currentExpertId) {
        this.selectSession(this.currentSession);
      }
    },
    goToExpertList() {
      this.$router.push('/expert-list');
    }
  },
  mounted() {
    this.loadSessions();
    connectChatSocket({
      userId: this.userInfo.id,
      role: 'user',
      onMessage: this.handleSocketMessage
    });
  },
  beforeDestroy() {
    closeChatSocket();
  },
  computed: {
    messages() {
      return this.messagesMap[this.currentExpertId] || [];
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 120px);
  min-height: 600px;
  margin: 20px auto;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
  background: #fff;
  max-width: 1200px;
}

/* 侧边栏样式 */
.sidebar {
  width: 320px;
  background: #2c3e50;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 24px;
  background: #1a2a3a;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
}

.logo i {
  font-size: 24px;
  margin-right: 12px;
  color: #42b983;
}

.sidebar-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

.session-filter {
  padding: 16px;
}

.search-input :deep(.el-input__inner) {
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: #fff;
}

.search-input :deep(.el-input__prefix) {
  color: rgba(255, 255, 255, 0.7);
}

.session-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 10px 10px;
}

.session-card {
  position: relative;
  display: flex;
  padding: 16px;
  border-radius: 12px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: rgba(255, 255, 255, 0.05);
}

.session-card:hover {
  background: rgba(255, 255, 255, 0.1);
}

.session-card.active {
  background: rgba(66, 185, 131, 0.2);
  border-left: 4px solid #42b983;
}

.session-avatar {
  position: relative;
  margin-right: 15px;
}

.online-status {
  position: absolute;
  bottom: -5px;
  right: -5px;
  padding: 2px 6px;
  background: #42b983;
  border-radius: 10px;
  font-size: 10px;
  color: white;
}

.session-info {
  flex: 1;
  min-width: 0;
  color: #fff;
}

.session-name {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.session-title {
  font-size: 13px;
  color: #42b983;
  margin-bottom: 8px;
}

.session-preview {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.6);
  display: flex;
  justify-content: space-between;
}

.preview-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 70%;
}

.preview-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.4);
}

.session-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  min-width: 20px;
  height: 20px;
  background: #e74c3c;
  color: white;
  border-radius: 10px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6px;
}

.empty-sessions {
  margin-top: 50px;
  color: rgba(255, 255, 255, 0.5);
}

/* 聊天区域样式 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.chat-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-info {
  display: flex;
  align-items: center;
}

.header-avatar {
  margin-right: 15px;
}

.header-text {
  display: flex;
  flex-direction: column;
}

.header-name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.header-status {
  font-size: 14px;
  color: #42b983;
}

.message-container {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #f5f7fa;
}

.chat-date {
  text-align: center;
  margin: 20px 0;
  position: relative;
}

.chat-date::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  width: 100%;
  height: 1px;
  background: #e0e6ed;
  z-index: 1;
}

.chat-date span {
  background: #f5f7fa;
  padding: 0 15px;
  position: relative;
  z-index: 2;
  color: #8492a6;
  font-size: 14px;
  font-weight: 500;
}

.message-wrapper {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
}

.message-wrapper.user {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 12px;
  align-self: flex-start;
}

.message-body {
  max-width: 70%;
}

.message-sender {
  font-size: 13px;
  color: #8492a6;
  margin-bottom: 4px;
}

.message-bubble {
  padding: 12px 18px;
  border-radius: 18px;
  position: relative;
  word-break: break-word;
  line-height: 1.6;
  font-size: 15px;
}

.message-wrapper.expert .message-bubble {
  background: #fff;
  color: #2c3e50;
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.message-wrapper.user .message-bubble {
  background: #42b983;
  color: white;
  border-bottom-right-radius: 4px;
  text-align: right;
}

.message-time {
  font-size: 12px;
  color: #8492a6;
  margin-top: 6px;
  text-align: right;
}

.typing-indicator {
  display: flex;
  margin-bottom: 24px;
}

.typing-bubble {
  padding: 12px 16px;
  background: #fff;
  border-radius: 18px;
  width: 60px;
  display: flex;
  justify-content: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.typing-bubble span {
  height: 8px;
  width: 8px;
  background: #42b983;
  border-radius: 50%;
  margin: 0 2px;
  display: inline-block;
  animation: typing 1.5s infinite ease-in-out;
}

.typing-bubble span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-bubble span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% { transform: translateY(0); }
  50% { transform: translateY(-8px); }
  100% { transform: translateY(0); }
}

.chat-footer {
  padding: 16px 24px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.message-input-wrapper {
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 24px;
  padding: 8px 16px;
}

.message-tools {
  display: flex;
  margin-right: 10px;
}

.tool-icon {
  font-size: 20px;
  color: #8492a6;
  margin-right: 12px;
  cursor: pointer;
  transition: color 0.3s;
}

.tool-icon:hover {
  color: #42b983;
}

.message-input {
  flex: 1;
}

.message-input :deep(.el-textarea__inner) {
  border: none;
  background: transparent;
  padding: 8px 0;
  font-size: 15px;
  resize: none;
  height: auto;
  line-height: 1.6;
}

.message-input :deep(.el-textarea__inner:focus) {
  box-shadow: none;
}

.message-send {
  margin-left: 12px;
}

.message-send .el-button {
  background: #42b983;
  border-color: #42b983;
}

.message-send .el-button:hover, 
.message-send .el-button:focus {
  background: #3ca776;
  border-color: #3ca776;
}

.empty-chat {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-chat-content {
  text-align: center;
  color: #8492a6;
}

.empty-chat-content i {
  font-size: 64px;
  margin-bottom: 24px;
  color: #d3dce6;
}

.empty-chat-content p {
  font-size: 18px;
  margin-bottom: 24px;
  color: #5e6d82;
}

@media (max-width: 768px) {
  .chat-container {
    flex-direction: column;
    height: calc(100vh - 80px);
    margin: 10px;
    border-radius: 12px;
  }
  
  .sidebar {
    width: 100%;
    height: 300px;
  }
  
  .chat-main {
    height: calc(100% - 300px);
  }
}
</style>
